package com.ruoyi.docdraw.controller;
import java.io.IOException;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.docdraw.domain.SysDoc;
import com.ruoyi.docdraw.domain.SysDocMaster;
import com.ruoyi.docdraw.domain.SysDocdrawSupplier;
import com.ruoyi.docdraw.domain.vo.SyncReqVo;
import com.ruoyi.docdraw.service.*;
import com.ruoyi.docdraw.vo.CheckDrawVersionVo;
import com.ruoyi.docdraw.vo.SysDocDrawRespVo;
import com.ruoyi.docdraw.vo.SysDocRespVo;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;


/**
 * 文档图纸Controller
 * 
 * @author lvtian
 * @date 2025-02-25
 */
@RestController
@RequestMapping("/system/docdraw")
public class SysDocDrawController extends BaseController
{
    @Autowired
    private ISysDocService sysDocService;

    @Autowired
    private ISysDocMasterService sysDocMasterService;

    @Autowired
    private ISysGDPService sysGDPService;
    @Autowired
    private ISysSupplierService sysSupplierService;
    @Autowired
    private ISysDocdrawSupplierService sysDocdrawSupplierService;

    /**
     * 查询文档图纸列表
     */
    @PreAuthorize("@ss.hasPermi('system:docdraw:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysDocMaster sysDocMaster)
    {
        // 获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        if(ObjectUtils.isEmpty(loginUser)){
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.UNAUTHORIZED);
            rspData.setMsg("用户未登录，请先登录");
            return rspData;
        }
        // 如果是管理员，则不需要设置 deptId，查询所有部门的数据
        Long deptId = user.getDeptId();
        List<SysDocMaster> sysDocMasters = null;
        if (user.isAdmin()) {
            sysDocMasters = sysDocMasterService.selectSysDocMasterList(sysDocMaster);
        } else {
            if (sysSupplierService.checkUserIsSupplier(user)) {
                // 是供应商
                SysDocdrawSupplier docdrawSupplier = new SysDocdrawSupplier();
                docdrawSupplier.setSupplierId(deptId);
                sysDocMasters = sysDocdrawSupplierService.selectJoinedList(docdrawSupplier, sysDocMaster.getDocName(), sysDocMaster.getDocNumber());
            } else {
                // 是租户
                sysDocMaster.setDeptId(deptId);
                sysDocMasters = sysDocMasterService.selectSysDocMasterList(sysDocMaster);
            }

        }

        startPage();

        List<SysDocRespVo> sysDocRespVos = sysDocMasterService.docMasterListProcessor(sysDocMasters);
        return getDataTable(sysDocRespVos);
    }

    /**
     * 历史版本
     * @param sysDocMasterId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:docdraw:list')")
    @GetMapping("/docHistoryList")
    public TableDataInfo docHistoryList(@RequestParam Long sysDocMasterId){

        SysDocMaster sysDocMasterDB = sysDocMasterService.selectSysDocMasterByDocMasterId(sysDocMasterId);
        startPage();
        List<SysDocRespVo> sysDocRespVos = sysGDPService.docMasterListProcessor(sysDocMasterDB);
        return getDataTable(sysDocRespVos);
    }


    @PreAuthorize("@ss.hasPermi('system:docdraw:list')")
    @GetMapping("/docDrawList")
    public TableDataInfo docDrawList(@RequestParam Long sysDocId){

        SysDoc sysDoc = sysDocService.selectSysDocByDocId(sysDocId);
        startPage();
        List<SysDocDrawRespVo> sysDocDrawRespVos = sysGDPService.docDrawListProcessor(sysDoc);
        return getDataTable(sysDocDrawRespVos);
    }

    /**
     * 检查是否当前图纸是否为最新版本
     * @param docOr
     * @return
     */
//    @Anonymous
    @GetMapping("/checkDrawVersion")
    @Log(title = "扫描二维码", businessType = BusinessType.SCAN)
    public AjaxResult checkDrawVersion(@RequestParam @NotBlank(message = "文档OR不能为空") String docOr, @RequestParam @NotBlank(message = "请传入组织参数") String deptId, HttpServletResponse response){
//        System.out.println("docOr=" + docOr);
//        System.out.println("deptId=" + deptId);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        LoginUser loginUser = SecurityUtils.getLoginUser();
        CheckDrawVersionVo vo = sysGDPService.checkDrawVersionByOr(docOr, deptId, loginUser.getUser());
        Long lasted = vo.getLasted();
        if(ObjectUtil.isNotNull(lasted)){
            return AjaxResult.success(vo.getMsg(),vo);
        }else {
            return AjaxResult.error(vo.getMsg(),vo);
        }
    }


    /**
     * 当前用户的前五次扫码 历史记录
     * @param response
     * @return
     */
    @GetMapping("/scanHistory")
    @Log(title = "查看扫码历史", businessType = BusinessType.OTHER)
    public AjaxResult scanHistory(HttpServletResponse response){

        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");

        return AjaxResult.success("success",sysGDPService.scanHistory(getUsername()));
    }



//
//    /**
//     * 同步选中的多个文档图纸
//     */
//    @PreAuthorize("@ss.hasPermi('system:docdraw:syncDoc')")
//    @Log(title = "文档图纸同步", businessType = BusinessType.UPDATE)
//    @PostMapping("/syncDocDraw")
//    public AjaxResult sync(@RequestBody List<Long> docMasterIds)
//    {
//        sysDocDrawService.syncDocDraw(docMasterIds);
//        return AjaxResult.success("已发送同步请求");
//    }
//
//
//    /**
//     * 租户管理员同步全部 文档图纸
//     */
//    @PreAuthorize("@ss.hasPermi('system:docdraw:allSyncDoc')")
//    @Log(title = "组织全部文档图纸同步", businessType = BusinessType.UPDATE)
//    @PostMapping("/allSyncDoc")
//    public AjaxResult allSyncDoc()
//    {
//        // 获取当前登录用户
//        LoginUser loginUser = SecurityUtils.getLoginUser();
//        Long deptId = null;
//        // 如果是管理员，则不需要设置 deptId，查询所有部门的数据
//        if (SecurityUtils.isAdmin(loginUser.getUserId())) {
//
//        } else {
//            // 如果不是管理员，只查询当前用户所属部门的数据
//            deptId = loginUser.getDeptId();
//        }
//        sysDocMasterService.syncDocDraw(deptId, loginUser.getUserId());
//        return AjaxResult.success("已发送同步请求");
//    }



    @Log(title = "windchill推送更新文档信息", businessType = BusinessType.UPDATE)
    @PostMapping("/windchill/put")
    public AjaxResult windchillPut(@RequestBody SyncReqVo reqVo){
        return AjaxResult.success("success",sysGDPService.insertAndUpdate(reqVo));
    }


    @Log(title = "下载图纸", businessType = BusinessType.EXPORT)
    @GetMapping("/download/drawStr")
    @PostAuthorize("@ss.hasPermi('system:docdraw:download')")
//    @Anonymous
    public AjaxResult downloadDrawStr(@RequestParam @NotNull Long drawId, HttpServletResponse response) throws IOException {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        return sysGDPService.downloadDrawStr(drawId, response, loginUser.getUser());
    }

    @Log(title = "下载图纸", businessType = BusinessType.EXPORT)
    @GetMapping("/download/draw")
    @PostAuthorize("@ss.hasPermi('system:docdraw:download')")
//    @Anonymous
    public void downloadDraw(@RequestParam @NotNull Long drawId, HttpServletResponse response) throws IOException {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        sysGDPService.downloadDraw(drawId, response, loginUser.getUser());
    }
}
